<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>🔍 Phase 1: 基础连接测试 (前端开发增强版)</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            margin: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            padding: 30px;
        }
        
        .header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid #eee;
        }
        
        .phase-navigation {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 15px;
            margin-bottom: 25px;
            padding: 20px;
            background: linear-gradient(135deg, #f8f9fa, #e9ecef);
            border-radius: 12px;
            border: 1px solid #dee2e6;
        }
        
        .phase-step {
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
            transition: all 0.3s ease;
            cursor: pointer;
        }
        
        .phase-step.completed {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .phase-step.completed:hover {
            background: #c1e2c8;
            transform: translateY(-1px);
        }
        
        .phase-step.current {
            background: #fff3cd;
            color: #856404;
            border: 2px solid #ffc107;
            font-weight: 600;
        }
        
        .phase-step.pending {
            background: #f8f9fa;
            color: #6c757d;
            border: 1px solid #dee2e6;
        }
        
        .phase-arrow {
            color: #6c757d;
            font-weight: bold;
        }
        
        .status-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .service-card {
            border: 2px solid #e3e3e3;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            transition: all 0.3s ease;
        }
        
        .service-card.online {
            border-color: #28a745;
            background: #f8fff9;
        }
        
        .service-card.offline {
            border-color: #dc3545;
            background: #fff8f8;
        }
        
        .service-card.testing {
            border-color: #ffc107;
            background: #fffef8;
        }
        
        .status-indicator {
            font-size: 24px;
            margin-bottom: 10px;
        }
        
        .test-buttons {
            display: flex;
            flex-direction: column;
            gap: 10px;
            margin-bottom: 20px;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s ease;
            width: 100%;
            margin-bottom: 10px;
            position: relative;
            overflow: hidden;
        }
        
        .btn-primary {
            background: #007bff;
            color: white;
        }
        
        .btn-primary:hover {
            background: #0056b3;
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0, 123, 255, 0.3);
        }
        
        .btn-success {
            background: #28a745;
            color: white;
        }
        
        .btn-success:hover {
            background: #1e7e34;
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(40, 167, 69, 0.3);
        }
        
        .log-area {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 15px;
            max-height: 250px;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            line-height: 1.4;
        }
        
        .log-entry {
            margin-bottom: 5px;
            padding: 2px 0;
        }
        
        .log-info { color: #0066cc; }
        .log-success { color: #00aa00; }
        .log-error { color: #cc0000; }
        .log-warning { color: #ff8800; }
        
        .overall-status {
            text-align: center;
            margin: 20px 0;
            padding: 15px;
            border-radius: 10px;
            font-weight: bold;
            font-size: 18px;
        }
        
        .overall-status.ready {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .overall-status.not-ready {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .overall-status.testing {
            background: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }
        
        .next-phase {
            text-align: center;
            margin-top: 30px;
            padding: 25px;
            background: linear-gradient(135deg, #6c757d, #495057);
            border-radius: 12px;
            color: white;
            transition: all 0.3s ease;
        }
        
        .next-phase.enabled {
            background: linear-gradient(135deg, #28a745, #20c997);
            cursor: pointer;
        }
        
        .next-phase.enabled:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 16px rgba(40, 167, 69, 0.3);
        }
        
        .next-phase button {
            background: rgba(255,255,255,0.2);
            color: white;
            border: 1px solid rgba(255,255,255,0.3);
            padding: 12px 24px;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 500;
            margin-top: 10px;
            transition: all 0.3s ease;
        }
        
        .next-phase button:hover:not(:disabled) {
            background: rgba(255,255,255,0.3);
            transform: scale(1.05);
        }
        
        .next-phase button:disabled {
            cursor: not-allowed;
            opacity: 0.6;
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            .status-grid {
                grid-template-columns: 1fr;
            }
            
            .phase-navigation {
                flex-wrap: wrap;
                gap: 10px;
            }
            
            .phase-step {
                font-size: 11px;
                padding: 6px 12px;
            }
        }
        
        /* 增强的API展示区域 */
        .api-display-section {
            margin-top: 30px;
            border: 2px solid #17a2b8;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 4px 12px rgba(23, 162, 184, 0.15);
        }
        
        .api-header {
            background: linear-gradient(135deg, #17a2b8, #138496);
            color: white;
            padding: 20px;
            font-weight: 600;
            position: relative;
        }
        
        .api-header::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: linear-gradient(90deg, #20c997, #17a2b8, #6f42c1);
        }
        
        .api-content {
            padding: 25px;
            background: #f8f9fa;
        }
        
        .api-section {
            margin-bottom: 25px;
        }
        
        .api-section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
        }
        
        .api-section h4 {
            color: #495057;
            margin: 0;
            font-size: 16px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .copy-btn {
            padding: 4px 8px;
            background: #6c757d;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 11px;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .copy-btn:hover {
            background: #5a6268;
            transform: scale(1.05);
        }
        
        .copy-btn.copied {
            background: #28a745;
            animation: pulse 0.6s ease;
        }
        
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.1); }
            100% { transform: scale(1); }
        }
        
        .api-block {
            background: #2c3e50;
            color: #ecf0f1;
            padding: 16px;
            border-radius: 8px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            overflow-x: auto;
            white-space: pre-wrap;
            line-height: 1.5;
            border-left: 4px solid #3498db;
            position: relative;
        }
        
        .api-block::before {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            width: 2px;
            background: linear-gradient(180deg, #3498db, #2c3e50);
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🔍 Phase 1: 基础连接测试</h1>
            <p>验证智能通知系统服务连接状态 + API展示 + Vue前端开发参考</p>
            
            <div class="phase-navigation">
                <div class="phase-step current">
                    🔄 Phase 1: 连接测试
                </div>
                <div class="phase-arrow">→</div>
                <div class="phase-step pending" onclick="goToPhase(2)">
                    ⭕ Phase 2: 认证测试
                </div>
                <div class="phase-arrow">→</div>
                <div class="phase-step pending">
                    ⭕ Phase 3: 发布测试
                </div>
                <div class="phase-arrow">→</div>
                <div class="phase-step pending">
                    ⭕ Phase 4: 列表测试
                </div>
                <div class="phase-arrow">→</div>
                <div class="phase-step pending">
                    ⭕ Phase 5: 审批测试
                </div>
            </div>
        </div>

        <div class="status-grid">
            <div class="service-card" id="mainServiceCard">
                <div class="status-indicator" id="mainServiceIcon">⭕</div>
                <h3>主通知服务</h3>
                <p><strong>http://localhost:48081</strong></p>
                <p id="mainServiceStatus">等待测试...</p>
                <p id="mainServiceDetails"></p>
            </div>

            <div class="service-card" id="mockServiceCard">
                <div class="status-indicator" id="mockServiceIcon">⭕</div>
                <h3>Mock School API</h3>
                <p><strong>http://localhost:48082</strong></p>
                <p id="mockServiceStatus">等待测试...</p>
                <p id="mockServiceDetails"></p>
            </div>
        </div>

        <div class="overall-status testing" id="overallStatus">
            🔄 准备开始连接测试...
        </div>

        <div class="test-buttons">
            <button class="btn btn-primary" onclick="testMainService()">
                🔧 测试主通知服务 (48081)
            </button>
            <button class="btn btn-primary" onclick="testMockService()">
                🔧 测试Mock School API (48082)
            </button>
            <button class="btn btn-success" onclick="testBothServices()">
                🚀 测试所有服务
            </button>
        </div>

        <!-- 增强的API展示区域 -->
        <div class="api-display-section">
            <div class="api-header">
                💻 实时API调用展示 & Vue 3 + TypeScript 前端开发参考
            </div>
            <div class="api-content">
                <div class="api-section">
                    <div class="api-section-header">
                        <h4>🔄 当前API调用</h4>
                        <button class="copy-btn" onclick="copyToClipboard('apiCall', this)">复制</button>
                    </div>
                    <div class="api-block" id="apiCall">等待API调用...</div>
                </div>
                
                <div class="api-section">
                    <div class="api-section-header">
                        <h4>📥 API响应结果</h4>
                        <button class="copy-btn" onclick="copyToClipboard('apiResponse', this)">复制</button>
                    </div>
                    <div class="api-block" id="apiResponse">等待API响应...</div>
                </div>
                
                <div class="api-section">
                    <div class="api-section-header">
                        <h4>🌟 Vue 3 + TypeScript 参考代码</h4>
                        <button class="copy-btn" onclick="copyToClipboard('vueCode', this)">复制代码</button>
                    </div>
                    <div class="api-block" id="vueCode">等待生成Vue参考代码...</div>
                </div>
            </div>
        </div>

        <div>
            <h3>📋 连接测试日志</h3>
            <div class="log-area" id="logArea">
                <div class="log-entry log-info">[INFO] Phase 1 基础连接测试页面已加载 (前端开发增强版)</div>
                <div class="log-entry log-info">[INFO] 等待用户开始测试...</div>
            </div>
        </div>
        
        <!-- 下一阶段按钮 -->
        <div class="next-phase" id="nextPhase">
            <h4>🎯 进入下一阶段</h4>
            <p>连接测试成功后，可以进入认证系统测试</p>
            <button onclick="goToPhase2()" disabled id="nextPhaseBtn">
                🔐 Phase 2: 智能认证测试
            </button>
        </div>
    </div>

    <script>
        // 全局状态 - 保持原样
        const testState = {
            mainService: false,
            mockService: false,
            logs: []
        };

        // 添加日志 - 保持原样
        function addLog(message, type = 'info') {
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = `[${timestamp}] [${type.toUpperCase()}] ${message}`;
            testState.logs.push({ message: logEntry, type });
            
            const logArea = document.getElementById('logArea');
            const logDiv = document.createElement('div');
            logDiv.className = `log-entry log-${type}`;
            logDiv.textContent = logEntry;
            logArea.appendChild(logDiv);
            logArea.scrollTop = logArea.scrollHeight;
            
            console.log(logEntry);
        }

        // API展示函数 - 修复版本
        function displayApiCall(method, url, headers) {
            const apiCallDiv = document.getElementById('apiCall');
            let callInfo = `🌐 API调用信息:
${method} ${url}

📤 请求头:`;
            
            if (headers) {
                Object.entries(headers).forEach(([key, value]) => {
                    callInfo += `\n${key}: ${value}`;
                });
            }
            
            apiCallDiv.textContent = callInfo;
        }

        function displayApiResponse(response) {
            const apiResponseDiv = document.getElementById('apiResponse');
            apiResponseDiv.textContent = JSON.stringify(response, null, 2);
        }

        function displayVueCode(serviceName, method, url) {
            const vueCodeDiv = document.getElementById('vueCode');
            const baseURL = url.split('/')[0] + '//' + url.split('/')[2];
            const vueCode = `// Vue 3 + TypeScript 服务连接示例
// 文件: src/services/${serviceName}Service.ts

class ${serviceName}Service {
  private baseURL = '${baseURL}';

  async checkConnection() {
    try {
      const response = await fetch('${url}', {
        method: '${method}',
        headers: {
          'Content-Type': 'application/json',
          'tenant-id': '1'
        }
      });

      if (response.ok) {
        const data = await response.text();
        return { success: true, data };
      } else {
        return { success: false, error: 'HTTP ' + response.status };
      }
    } catch (error) {
      return { success: false, error: error.message };
    }
  }
}

// Vue组件中使用:
import { ref, onMounted } from 'vue';

const service = new ${serviceName}Service();
const isOnline = ref(false);

const checkService = async () => {
  const result = await service.checkConnection();
  isOnline.value = result.success;
};

onMounted(checkService);`;
            
            vueCodeDiv.textContent = vueCode;
        }

        // 更新服务状态显示 - 保持原样
        function updateServiceStatus(service, isOnline, details = '') {
            const cardId = `${service}ServiceCard`;
            const iconId = `${service}ServiceIcon`;
            const statusId = `${service}ServiceStatus`;
            const detailsId = `${service}ServiceDetails`;
            
            const card = document.getElementById(cardId);
            const icon = document.getElementById(iconId);
            const status = document.getElementById(statusId);
            const detailsEl = document.getElementById(detailsId);
            
            if (isOnline) {
                card.className = 'service-card online';
                icon.textContent = '✅';
                status.textContent = '服务在线';
                status.style.color = '#28a745';
            } else {
                card.className = 'service-card offline';
                icon.textContent = '❌';
                status.textContent = '服务离线';
                status.style.color = '#dc3545';
            }
            
            detailsEl.textContent = details;
            testState[`${service}Service`] = isOnline;
            updateOverallStatus();
        }

        // 设置测试中状态 - 保持原样
        function setTestingStatus(service) {
            const cardId = `${service}ServiceCard`;
            const iconId = `${service}ServiceIcon`;
            const statusId = `${service}ServiceStatus`;
            
            document.getElementById(cardId).className = 'service-card testing';
            document.getElementById(iconId).textContent = '🔄';
            document.getElementById(statusId).textContent = '测试中...';
            document.getElementById(statusId).style.color = '#856404';
        }

        // 更新整体状态 - 保持原样
        function updateOverallStatus() {
            const overallEl = document.getElementById('overallStatus');
            
            if (testState.mainService && testState.mockService) {
                overallEl.className = 'overall-status ready';
                overallEl.textContent = '🎉 所有服务就绪！可以进行下一阶段测试';
            } else if (testState.mainService || testState.mockService) {
                overallEl.className = 'overall-status not-ready';
                overallEl.textContent = '⚠️ 部分服务异常，请检查服务状态';
            } else {
                overallEl.className = 'overall-status not-ready';
                overallEl.textContent = '❌ 服务连接失败，请检查服务是否启动';
            }
        }

        // 测试主服务 - 增加API展示
        async function testMainService() {
            addLog('开始测试主通知服务连接...');
            setTestingStatus('main');
            
            const url = 'http://localhost:48081/admin-api/test/notification/api/ping';
            const headers = {
                'Content-Type': 'application/json',
                'tenant-id': '1'
            };
            
            displayApiCall('GET', url, headers);
            displayVueCode('Main', 'GET', url);
            
            try {
                const response = await fetch(url, {
                    method: 'GET',
                    headers: headers
                });

                const responseData = {
                    success: response.ok,
                    status: response.status,
                    data: response.ok ? await response.text() : await response.text()
                };

                displayApiResponse(responseData);

                if (response.ok) {
                    addLog(`主服务连接成功: ${responseData.data}`, 'success');
                    updateServiceStatus('main', true, `响应: ${responseData.data.substring(0, 50)}...`);
                } else {
                    addLog(`主服务连接失败: HTTP ${response.status}`, 'error');
                    updateServiceStatus('main', false, `HTTP ${response.status}`);
                }
            } catch (error) {
                displayApiResponse({ success: false, error: error.message });
                addLog(`主服务连接异常: ${error.message}`, 'error');
                updateServiceStatus('main', false, error.message);
            }
        }

        // 测试Mock服务 - 增加API展示
        async function testMockService() {
            addLog('开始测试Mock School API连接...');
            setTestingStatus('mock');
            
            const url = 'http://localhost:48082/mock-school-api/auth/health';
            const headers = {
                'Content-Type': 'application/json'
            };
            
            displayApiCall('GET', url, headers);
            displayVueCode('Mock', 'GET', url);
            
            try {
                const response = await fetch(url, {
                    method: 'GET',
                    headers: headers
                });

                const responseData = {
                    success: response.ok,
                    status: response.status,
                    data: response.ok ? await response.json() : await response.text()
                };

                displayApiResponse(responseData);

                if (response.ok) {
                    addLog(`Mock API连接成功: ${responseData.data.message}`, 'success');
                    updateServiceStatus('mock', true, `消息: ${responseData.data.message}`);
                } else {
                    addLog(`Mock API连接失败: HTTP ${response.status}`, 'error');
                    updateServiceStatus('mock', false, `HTTP ${response.status}`);
                }
            } catch (error) {
                displayApiResponse({ success: false, error: error.message });
                addLog(`Mock API连接异常: ${error.message}`, 'error');
                updateServiceStatus('mock', false, error.message);
            }
        }

        // 测试所有服务 - 保持原样
        async function testBothServices() {
            addLog('========== 开始全面连接测试 ==========');
            document.getElementById('overallStatus').className = 'overall-status testing';
            document.getElementById('overallStatus').textContent = '🔄 正在测试所有服务...';
            
            // 并行测试两个服务
            await Promise.all([testMainService(), testMockService()]);
            
            addLog('========== 连接测试完成 ==========');
            
            // 检查是否启用下一阶段
            if (testState.mainService && testState.mockService) {
                enableNextPhase();
            }
        }

        // 启用下一阶段
        function enableNextPhase() {
            const nextPhase = document.getElementById('nextPhase');
            const nextBtn = document.getElementById('nextPhaseBtn');
            
            nextPhase.classList.add('enabled');
            nextBtn.disabled = false;
            
            addLog('🎯 Phase 2 已解锁，可以进行认证系统测试', 'success');
        }

        // 复制到剪贴板功能
        function copyToClipboard(elementId, buttonEl) {
            const element = document.getElementById(elementId);
            const text = element.textContent;
            
            navigator.clipboard.writeText(text).then(() => {
                const originalText = buttonEl.textContent;
                buttonEl.textContent = '已复制!';
                buttonEl.classList.add('copied');
                
                setTimeout(() => {
                    buttonEl.textContent = originalText;
                    buttonEl.classList.remove('copied');
                }, 2000);
            }).catch(() => {
                // 备用方案
                const textArea = document.createElement('textarea');
                textArea.value = text;
                document.body.appendChild(textArea);
                textArea.select();
                document.execCommand('copy');
                document.body.removeChild(textArea);
                
                buttonEl.textContent = '已复制!';
                buttonEl.classList.add('copied');
                setTimeout(() => {
                    buttonEl.textContent = '复制';
                    buttonEl.classList.remove('copied');
                }, 2000);
            });
        }

        // 阶段导航功能
        function goToPhase(phaseNumber) {
            if (phaseNumber === 2) {
                addLog('准备进入 Phase 2: 认证测试');
                if (confirm('是否进入 Phase 2: 智能认证系统测试页面？')) {
                    window.location.href = 'phase2-authentication-enhanced.html';
                }
            }
        }

        // 进入Phase 2
        function goToPhase2() {
            if (!testState.mainService || !testState.mockService) {
                addLog('请先完成所有服务连接测试', 'warning');
                return;
            }
            
            addLog('🚀 准备进入 Phase 2: 智能认证系统测试');
            
            if (confirm('连接测试完成！是否继续到 Phase 2: 智能认证系统测试？')) {
                window.location.href = 'phase2-authentication-enhanced.html';
            }
        }

        // 页面加载完成后自动进行一次测试 - 保持原样
        window.addEventListener('DOMContentLoaded', function() {
            addLog('页面加载完成，准备进行初始连接测试');
            setTimeout(() => {
                testBothServices();
            }, 1000);
        });
    </script>
</body>
</html>